﻿using System;
using System.Collections.Generic;
using UFIDA.U9.AP.Payment;
using UFIDA.U9.Base.DTOs;
using UFIDA.U9.CBO.FI.PropertyTypes;
using UFIDA.U9.CBO.SCM.Item;
using UFIDA.U9.PM.ASN;
using UFIDA.U9.PM.PO;
using UFIDA.U9.PM.Rcv;
using UFSoft.UBF.Business;
using UFSoft.UBF.Eventing;

namespace UFIDA.U9.Cust.YHPlugInBE
{
    ///必需要引用基类  IEventSubscriber 
    internal class ProcessForPayReqFundjy : IEventSubscriber
    {
        long DocID = 0;
        public void Notify(params object[] args)
        {
            if (args == null || args.Length == 0 || !(args[0] is UFSoft.UBF.Business.EntityEvent)) return;
            BusinessEntity.EntityKey key = ((UFSoft.UBF.Business.EntityEvent)args[0]).EntityKey;
            if (key == null || key.GetEntity() == null) return;

            //请款
            UFIDA.U9.AP.Payment.PayReqFundHead pref = key.GetEntity() as UFIDA.U9.AP.Payment.PayReqFundHead;
            if (pref == null) return;

            if (pref.DocStatus != CBO.FI.Enums.InDirectHandleBillDocStatusEnum.Open)
                return;

            #region 请款单根据填写比例更更原始金额
            if (String.IsNullOrEmpty(pref.DescFlexField.PrivateDescSeg3))
                pref.DescFlexField.PrivateDescSeg3 = "1";

            decimal docmny = 0;
            foreach (var line in pref.PayReqFundUses)
            {
                //预付款 或者标准款
                if (line.ReqFundUse == AP.Enums.RequestFundUseEnum.PrePay)
                {
                    //行修改
                    decimal linemny = 0;
                    foreach (var subline in line.PayReqFundDetails)
                    {
                        POLine poline = POLine.Finder.FindByID(subline.SrcDataID);
                        if (poline == null) throw new Exception("查询订单行为空");
                        
                        decimal qkje=Math.Round(poline.TotalMnyFC * decimal.Parse(pref.DescFlexField.PrivateDescSeg3),2);
                        //计算最大可请款金额,公式参考请款单界面报错信息
                        decimal maxje = poline.MaxPrePayMoneyAC + poline.TotalFeeAC - poline.PrePayMoneyAC 
                            - poline.TotalPrePayedMnyAC - poline.TotalPayedMnyAC;
                        if(qkje>maxje) qkje = maxje;

                        subline.RFMoney.TotalMoney = qkje;// 	明细请款金额
                        subline.RFPayMoney = qkje;//请款付款金额	
                        subline.PUAmount = subline.RFMoney.TotalMoney/subline.Price; //请款数量

                        linemny += qkje;
                    }

                    line.RFTotalMoney = linemny;//行请款金额
                    line.RFPayMoney = linemny;// 请款付款金额
                    line.AcmPayFCMoney = linemny;//付款本币金额
                    line.RFPayMoney = linemny; //请款付款金额
                    docmny += linemny;
                }

            }

            pref.RFTotalMoney = docmny;
            pref.FCTotalMoney = docmny;

        }

        #endregion
        
    }

}
